package com.shuqi.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.shuqi.activity.adapter.BookSearchParentAdapter;
import com.shuqi.activity.viewport.BookSearchTabSlidingView;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.SearchPopupWindow;
import com.shuqi.common.Constant;
import com.shuqi.common.FunctionsSwitch;
import com.shuqi.common.ViewHelpProvider;
import com.shuqi.common.ViewHelpProvider.ViewHelpHandleType;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.SearchHistoryDao;
import com.shuqi.database.dao.impl.VersionShowDao.VersionShowEnum;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.BookSearchModel;
import com.shuqi.model.OfferWallOpenModel;
import com.shuqi.model.bean.SearchAssociateInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 搜索主activity
 * 
 * @author linyuren
 * 
 */
public class BookSearchParentActivity extends FragmentActivityBase implements OnClickListener,
        IEventListener {

    private final static int INIT = EventTypeConstants.BASE;
    private final static int INITDATAPOPWORDSUCCESS = INIT + 1;
    private final static int INITDATAOFWUPDATE = INITDATAPOPWORDSUCCESS + 1;
    /** 搜索框部分 */
    private View mSearchContent;

    /** 子View数量 */
    private final int mChildViewCount = 4;

    private BookSearchModel model;

    /** 存储搜索联想返回数据 */
    private List<SearchAssociateInfo> mOnlineList;

    private BookSearchTabSlidingView mSlidingView;

    /** 搜索联想弹出框 */
    private SearchPopupWindow mSearchPopupWindow;

    /** 搜索联想词 */
    private String mSearchKeyWord = "";

    /** viewpaper */
    private ViewPager mViewPager;

    /** 弹出搜索框的黑色半透明背景 */
    private View mSearchBackground;

    /** 要弹出pop的顶部布局 */
    private RelativeLayout mRelSearchBox;

    /** 输入框 */
    private EditText mEditSearchBox = null;

    /** 清除按钮 */
    private ImageView mBtClearSearchbar;

    /** 隐藏键盘所用控件 */
    private View mSuperView;

    /** 页卡选项索引 */
    private int mCurIndex = 0;

    private BookSearchParentAdapter mAdapter;

    private CommonTitle title;

    private PopupWindow viewHelp;

    /** 精品红点 */
    private OfferWallOpenModel ofwModel;
    String ofwUpdateDate = "";

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    break;
                case INITDATAOFWUPDATE:
                    setOfwUpdate();
                    break;
                case INITDATAPOPWORDSUCCESS:
                    /** 弹出联想框 */
                    mSearchPopupWindow.showJudgePW(BookSearchParentActivity.this, mSearchKeyWord,
                            mRelSearchBox, mOnlineList);
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_booksearchparent);
        model = new BookSearchModel(this);
        model.addEventListener(this);
        ofwModel = new OfferWallOpenModel(this);
        ofwModel.addEventListener(this);
        handler.sendEmptyMessage(INIT);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        // Activity完全初始化完绑定标题的事件，防止多次点击误操作
        if (title != null) {
            title.setImageListener(this);
        } else {
            title = (CommonTitle) findViewById(R.id.title);
            title.setImageListener(this);
        }

        if (viewHelp == null || !viewHelp.isShowing()) {// 当前没有显示帮助界面时执行
            // 搜索帮助
            View parentView = findViewById(R.id.book_search_root);
            int resId = R.layout.view_help_shenma_search;
            VersionShowEnum vShowEnum = VersionShowEnum.view_help_shenma_search;

            viewHelp =
                    ViewHelpProvider.getInstance().handle(this, vShowEnum,
                            ViewHelpHandleType.layout, parentView, resId);
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.search_magnifyng:
                search();
                break;
            case R.id.bt_clear_searchbar:
                this.mEditSearchBox.setText("");
                break;
            case R.id.sliding_tvhotlist:
                switchTo(Constant.SLIDING_0, true);
                break;
            case R.id.sliding_tvman:
                switchTo(Constant.SLIDING_1, true);
                break;
            case R.id.sliding_tvwoman:
                switchTo(Constant.SLIDING_2, true);
                break;
            case R.id.sliding_tvall:
                switchTo(Constant.SLIDING_3, true);
                break;
            case R.id.title_right:
                boolean isShowHelp =
                        ViewHelpProvider.getInstance().isShow(
                                VersionShowEnum.view_help_shenma_search);
                if (!isShowHelp) {// 显示帮助界面不跳积分墙
                    gotoOfferWall();
                    StatisticsUtils.onEvent(BookSearchParentActivity.this,
                            StatisticsEventID.BOOKSQUARE_TO_OFW);
                }
                break;
            case R.id.title_left:
                gotoBookShelf();
                // ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
                // public void run() {
                // }
                // }, 300);
                StatisticsUtils.onEvent(BookSearchParentActivity.this,
                        StatisticsEventID.BOOKSQUARE_TO_BOOKSHELF);
                break;
        }
    }

    private void gotoBookShelf() {
        BookShelfActivity.showFromMainActivityGroup(this.getParent(), false);
    }

    private void gotoOfferWall() {
        Intent intent = new Intent(this.getParent(), OfferWallTopActivity.class);
        ActivityManager.getInstance().startNextActivity(intent, this.getParent());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (!FunctionsSwitch.isOfferWallUpdate(this) && this.title != null) {
            // TODO 消失红点
            title.setRightImage(R.drawable.bg_icon_offerwall_selector);
        }
        if (this.mSearchPopupWindow != null) {
            this.mSearchPopupWindow.closePW();
        }
    }


    /**
     * 搜索联想跳转到搜索结果页
     * 
     * @param keyWord关键词
     * */
    public void jumpBookSearchResultActivity(String keyWord) {
        this.mEditSearchBox.setText(keyWord);
        this.mEditSearchBox.setSelection(keyWord.trim().length());
        if (this.mSearchPopupWindow != null) {
            this.mSearchPopupWindow.closePW();
        }
        Intent intent = new Intent(this, BookSearchResultActivity.class);
        intent.putExtra("keyword", keyWord);
        ActivityManager.getInstance().startNextActivityForResult(intent,
                Activity.RESULT_FIRST_USER, this);

        SearchHistoryDao.getInstance().saveSearchHistory(keyWord); // 保存到数据库
    }

    /**
     * 是否显示搜索框背景
     * 
     * @param isShow
     * */
    public void mShowSearchBackGround(boolean isShow) {
        if (isShow) {
            this.mSearchBackground.setVisibility(View.VISIBLE);
        } else {
            this.mSearchBackground.setVisibility(View.GONE);
        }
    }

    private void setOfwUpdate() {

        if (ofwUpdateDate.compareTo(FunctionsSwitch.getOfferWallUpdateDate(this)) > 0) {
            FunctionsSwitch.setOfferWallUpdate(this, true);
            FunctionsSwitch.setOfferWallUpdateDate(this, ofwUpdateDate);
        }

        if (FunctionsSwitch.isOfferWallUpdate(this)) {
            // 显示红点
            title.setRightImage(R.drawable.bg_icon_offerwall_red_selector);
        }
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null) {
                    if (data instanceof String) {
                        this.ofwUpdateDate = (String) data;
                        handler.sendEmptyMessage(INITDATAOFWUPDATE);
                    } else {
                        this.mOnlineList = (List<SearchAssociateInfo>) data;
                        handler.sendEmptyMessage(INITDATAPOPWORDSUCCESS);
                    }
                }
            default:
                // TOTO 无网络提示
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mEditSearchBox != null) {
            mEditSearchBox.setText("");
        }
        if (this.mSearchPopupWindow != null) {
            this.mSearchPopupWindow.closePW();
        }
    }

    private OnEditorActionListener editorListener = new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search();
                return true;
            }
            return false;
        }
    };

    /** 初始化 */
    private void activityLogicForward() {
        init();
        initPopWindow();
        initSetOnClickListener();
    }


    /** 初始化 */
    private void init() {
        this.mSearchContent = (View) findViewById(R.id.searchinto_content);

        this.mEditSearchBox = (EditText) findViewById(R.id.edit_searchbox);
        this.mRelSearchBox = (RelativeLayout) findViewById(R.id.rl_search_box);
        this.mBtClearSearchbar = (ImageView) findViewById(R.id.bt_clear_searchbar);

        this.mSlidingView = (BookSearchTabSlidingView) findViewById(R.id.slidingview_top_view);

        this.mViewPager = (ViewPager) findViewById(R.id.search_content_viewpaper);
        this.mViewPager.setOffscreenPageLimit(mChildViewCount);

        this.mSearchBackground = (View) findViewById(R.id.search_background);

        this.mSuperView = (View) findViewById(R.id.superView);

        this.mAdapter = new BookSearchParentAdapter(getSupportFragmentManager(), this);
        this.mViewPager.setAdapter(mAdapter);

        this.mSlidingView.setViewPager(mViewPager);
        this.switchTo(this.mCurIndex, false);

        this.title = (CommonTitle) findViewById(R.id.title);
        // this.title.setImageListener(this);
        this.title.setStyle(true, false);
    }

    /** 初始化弹出框 */
    private void initPopWindow() {
        this.mSearchPopupWindow = new SearchPopupWindow(this);

        this.mEditSearchBox.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mEditSearchBox.getText().toString())) {
                    mEditSearchBox.setText("");
                    // mSearchPopupWindow.showJudgePW(BookSearchParentActivity.this, "",
                    // mRelSearchBox, null);
                } else {
                    model.loadData(mEditSearchBox.getText().toString(), "other");
                    mSearchKeyWord = mEditSearchBox.getText().toString();
                }
            }
        });

        final View clearSearch = (View) findViewById(R.id.clear_search_content);

        this.mEditSearchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void afterTextChanged(Editable s) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    clearSearch.setVisibility(View.GONE);
                    /** 弹出搜索历史 */
                    mSearchPopupWindow.showJudgePW(BookSearchParentActivity.this, s.toString(),
                            mRelSearchBox, null);
                } else {
                    clearSearch.setVisibility(View.VISIBLE);
                    model.loadData(s.toString(), "other");
                    mSearchKeyWord = s.toString();
                }
            }
        });
    }

    /** 设置控件监听事件 */
    private void initSetOnClickListener() {

        for (int i = 0; i < mChildViewCount; i++) {
            mSlidingView.setOnClickListener(i, this);
        }

        mSuperView.setOnTouchListener(new ItemTouchEvent());

        mBtClearSearchbar.setOnClickListener(this);

        findViewById(R.id.search_magnifyng).setOnClickListener(this);

        mEditSearchBox.setOnEditorActionListener(editorListener);

        if (FunctionsSwitch.isOfferWallOpen(this)) {
            this.title.setStyle(true, true);
            // this.title.setImageListener(this);
            ofwModel.loadData(this);
        } else {
            this.title.setStyle(true, false);
        }
    }

    /**
     * 切换至指定页面
     * 
     * @param index 页面索引
     * @param isAnim 是否带动画
     */
    private void switchTo(int index, boolean isAnim) {
        this.mViewPager.setCurrentItem(index, isAnim);
        if (!isAnim) {
            this.mSlidingView.setSite(index);
        }
    }

    /** 点击搜索按钮执行 */
    private void search() {
        String keyWord = ((EditText) this.findViewById(R.id.edit_searchbox)).getText().toString();
        if (keyWord != null && keyWord.trim().length() != 0) {
            if (this.mSearchPopupWindow != null) {
                this.mSearchPopupWindow.closePW();
            }
            Intent intent = new Intent(this, BookSearchResultActivity.class);
            intent.putExtra("keyword", keyWord);
            ActivityManager.getInstance().startNextActivityForResult(intent, RESULT_FIRST_USER,
                    this);

            SearchHistoryDao.getInstance().saveSearchHistory(keyWord); // 保存到数据库
            mSearchPopupWindow.closePW();
            StatisticsUtils.onEvent(this, StatisticsEventID.BOOKSEARCH_INPUT_KEYWORD);
        } else {
            ToastUtil.showToastFullyCustomizable(this, "请输入关键字");
            return;
        }
    }



    /** 隐藏键盘监听事件 */
    private class ItemTouchEvent implements OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_MOVE) {

            } else if (event.getAction() == MotionEvent.ACTION_UP) {

            } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                Util.inputMethodControl(BookSearchParentActivity.this, false);
            }
            return false;
        }
    }

    /** 是否正在显示或隐藏SearchBox */
    private boolean mIsRunningAnim = false;

    public boolean mGetIsShowSearchBox() {
        return mIsShowSearchBox;
    }

    /** isShowSearchBox是否显示 */
    private boolean mIsShowSearchBox = true;

    /**
     * 根据当前SearchBox当前状态，动态的显示隐藏SearchBox
     */
    public boolean mChangeSearchBoxStates() {
        if (mIsRunningAnim) {
            return false;
        }
        mIsRunningAnim = true;
        final int height = mSearchContent.getHeight();
        final RelativeLayout.LayoutParams params =
                (android.widget.RelativeLayout.LayoutParams) mSearchContent.getLayoutParams();

        new Thread() {
            @Override
            public void run() {
                final int count = 30;
                for (int i = 0; i <= count; i++) {
                    if (mIsShowSearchBox) {
                        params.topMargin = -1 * i * height / count;
                    } else {
                        params.topMargin = -1 * (count - i) * height / count;
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            mSearchContent.setLayoutParams(params);
                        }
                    });
                    try {
                        sleep(6);
                    } catch (Exception e) {
                    }
                }
                try {
                    sleep(300);
                } catch (Exception e) {
                }
                mIsShowSearchBox = !mIsShowSearchBox;
                mIsRunningAnim = false;
            }
        }.start();
        return true;
    }

}
